﻿using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Om.Camera;
using Om.Core.Extension;
using Om.Core.Singleton;
using OptoMeasure.Extension;
using OptoMeasure.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace OptoMeasure
{
    /// <summary>
    /// MainView.xaml 的交互逻辑
    /// </summary>
    public partial class MainView : UserControl
    {
        public MainView()
        {
            InitializeComponent();
            var vm = App.Current.ServiceProvider.GetRequiredService<MainViewModel>();
            DataContext = vm;

            this.Loaded+= OnLoaded;
        }

        private async void OnLoaded(object sender, RoutedEventArgs e)
        {
            var cameraList = DevicesManager.Instance.GetBaseCameras();
            foreach (var camera in cameraList)
            {
                try
                {
                    var cameraName = DevicesManager.Instance.GetCameraName(camera.Key);
                    if(!DevicesConfig.Instance.CameraIds.ContainsKey(cameraName))
                        continue;

                    await camera.Value.GetCameraList();
                    var key = DevicesConfig.Instance.CameraIds[cameraName];
                    await camera.Value.Connect(key);
                }
                catch (Exception exception)
                {
                }
            }


            WeakReferenceMessenger.Default.Send(new object(), MsgToken.CameraConnectedChanged);
        }
    }
}
